package com.yz.group1.group_1.controller;

import com.yz.group1.group_1.entity.Hospitalization;
import com.yz.group1.group_1.service.HospitalizationService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/hospitalization")
public class HospitalizationController {

    @Autowired
    private HospitalizationService hospitalizationService;

    // 已有功能：提交住院申请
    @PostMapping("/save")
    public void saveHospitalization(@RequestBody Hospitalization hospitalization,
                                    HttpServletResponse response) {
        try {
            hospitalization.setStatus(0); // 默认状态为待审核
            System.out.println("接收住院申请：" + hospitalization);
            boolean success = hospitalizationService.save(hospitalization);
            if (!success) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "保存失败，数据库操作未执行");
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "保存失败：" + e.getMessage());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    // 新增功能：查看住院申请记录（支持按患者ID搜索）
    @GetMapping("/list")
    public List<Hospitalization> getHospitalizationList(
            @RequestParam(required = false) Long patientId) { // 患者ID为可选参数
        return hospitalizationService.getHospitalizationsByPatientId(patientId);
    }
}